package cn.waka.sys.admin.controller;

import java.util.Collection;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.Menu;
import cn.waka.sys.admin.service.MenuService;

@Controller
@SessionAttributes
public class MainController extends BaseController implements InitializingBean {
    @Value("${server.context.path}")
    private String contextPath;
    private MenuService menuService;

    @GetMapping(path = "/main")
    public ModelAndView index(@SessionAttribute(name = "uid", required = false) Object uid, @SessionAttribute(name = "authorize", required = false) String authorize) {
        ModelAndView mv = new ModelAndView();
        if (uid == null) {
            mv.setViewName("redirect:" + contextPath + "login");
            return mv;
        }
        Collection<Menu> topMenus = menuService.findTopAll(authorize);
        mv.addObject("menuTree", topMenus);
        mv.setViewName("main/index");
        return mv;
    }

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    @GetMapping(path = "/")
    public ModelAndView index1(ModelAndView mv) {
        mv.setViewName("redirect:" + contextPath + "main");
        return mv;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!contextPath.endsWith("/")) {
            contextPath += "/";
        }
    }
}
